//
//  CLHomeViewController.m
//  JG
//
//  Created by 程龙 on 2023/7/27.
//

#import "CLHomeViewController.h"
#import "WWKApi.h"
#import "CLMainViewController.h"
#import "CLWorkViewController.h"
#import <TZImagePickerController/TZImagePickerController.h>
@interface CLHomeViewController ()<TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    UILabel *cl_iconLable;
    UIButton* cl_loginBtn;
    UIButton* cl_workloginBtn;
}

@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@end

@implementation CLHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // self.gk_navTitle = @"首页";
    self.gk_navigationBar.hidden = YES;
    
    UIImageView *cl_iconView = [[UIImageView alloc]init];
    cl_iconView.frame = CGRectMake((CLWIDTH-150*CLSCALE/2)/2, CL_SizeStatusBarAndNavigationBarHeight+30*CLSCALE, 150*CLSCALE/2, 150*CLSCALE/2);
    cl_iconView.image = [UIImage imageNamed:@"tk"];
    [self.view addSubview:cl_iconView];
    
    cl_iconLable = [[UILabel alloc]init];
    cl_iconLable.frame = CGRectMake(0, CLSCALE_Y(cl_iconView)+24*CLSCALE, CLWIDTH, 24*CLSCALE);
    cl_iconLable.font = CLFONT(24);
    cl_iconLable.textColor = CLUIColorFromHEX(0x161C24);
    cl_iconLable.textAlignment = NSTextAlignmentCenter;
    cl_iconLable.text = @"请选择登录身份";
    [self.view addSubview:cl_iconLable];
    
//    UILabel *cl_iconLable1 = [[UILabel alloc]init];
//    cl_iconLable1.frame = CGRectMake(0, CLSCALE_Y(cl_iconLable)+80*CLSCALE, CLWIDTH, 20*CLSCALE);
//    cl_iconLable1.font = CLFONT(10);
//    cl_iconLable1.textColor = CLUIColorFromHEX(0X000000);
//    cl_iconLable1.textAlignment = NSTextAlignmentCenter;
//    cl_iconLable1.text = [NSString stringWithFormat:@"测试版本：%@",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]];
//    [self.view addSubview:cl_iconLable1];
    
    cl_loginBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect] ;
    cl_loginBtn.frame = CGRectMake(30*CLSCALE,CLSCALE_Y(cl_iconLable)+70*CLSCALE, CLWIDTH -30*CLSCALE*2, 40*CLSCALE) ;
    [cl_loginBtn setTitle:@"我是雨虹员工" forState:UIControlStateNormal] ;
    cl_loginBtn.backgroundColor = CLUIColorFromHEX(0xD7000F);
    [cl_loginBtn setTitleColor: [UIColor whiteColor ] forState:UIControlStateNormal] ;
    [cl_loginBtn jk_cornerRadius:4*CLSCALE strokeSize:1*CLSCALE color:CLUIColorFromHEX(0xEAE9FF)];
    [cl_loginBtn addTarget: self action: @selector(cl_loginBtn) forControlEvents: UIControlEventTouchDown] ;
    [self.view addSubview:cl_loginBtn] ;
    

    
    cl_workloginBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect] ;
    cl_workloginBtn.frame = CGRectMake(30*CLSCALE,CLSCALE_Y(cl_loginBtn)+30*CLSCALE, CLWIDTH -30*CLSCALE*2, 40*CLSCALE) ;
   // cl_workloginBtn.frame = CGRectMake(30*CLSCALE,CLSCALE_Y(cl_iconLable)+70*CLSCALE, CLWIDTH -30*CLSCALE*2, 40*CLSCALE) ;

    [cl_workloginBtn setTitle:@"我是雨虹合作伙伴" forState:UIControlStateNormal] ;
    cl_workloginBtn.backgroundColor = CLUIColorFromHEX(0xFF9B00);
    [cl_workloginBtn setTitleColor: [UIColor whiteColor ] forState:UIControlStateNormal] ;
    [cl_workloginBtn jk_cornerRadius:4*CLSCALE strokeSize:1*CLSCALE color:CLUIColorFromHEX(0xEAE9FF)];
    [cl_workloginBtn addTarget: self action: @selector(cl_workloginBtn) forControlEvents: UIControlEventTouchDown] ;
    [self.view addSubview:cl_workloginBtn] ;


    
}
- (void)cl_viewWill{
    [self viewWillAppear:YES];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    

    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusNotReachable || status == AFNetworkReachabilityStatusUnknown) {
            //无网络链接
            NSLog(@"无网络链接------------");
            Dialog()
            //出现动画
                .wShowAnimationSet(AninatonZoomIn)
            //消失动画
                .wHideAnimationSet(AninatonZoomOut)
                .wEventCancelFinishSet(^(id anyID, id otherData) {

                })
                .wEventOKFinishSet(^(id anyID, id otherData) {
                    [self viewWillAppear:YES];
                })
                .wTitleSet(@"温馨提示")
                .wMessageSet(@"请接入网络")
                .wOKTitleSet(@"重新请求")
                .wCancelTitleSet(@"取消")
                .wMessageColorSet(DialogColor(0x333333))
                .wTitleColorSet(DialogColor(0x666666))
                .wOKColorSet([UIColor orangeColor])
                .wCancelColorSet([UIColor blueColor])
                .wTitleFontSet(15)
                .wTypeSet(DialogTypeNornal).wStart();
            

        } else {
            [[AFNetworkReachabilityManager sharedManager] stopMonitoring];

            NSLog(@"网络链接------------");
            
            if([[CLTool cl_getUser:@"loginType"] isEqualToString:@"1"]){
                if([CLTool cl_getUser:@"workToken"].length != 0){
                    CLWorkViewController *vc = [[CLWorkViewController alloc]init];
                    vc.address = url_one_login;
                //    vc.address = @"https://ssouat.yuhong.com.cn/cp/tt/index.html";
                    [self.navigationController pushViewController:vc animated:YES];
                }
                
                
                return;
            }
            
            [ZBRequestManager requestWithConfig:^(ZBURLRequest *request){
                request.path=url_token;
                request.methodType=ZBMethodTypePOST;
            }  success:^(id responseObject,ZBURLRequest * request){
                if ([[NSString stringWithFormat:@"%@",responseObject[@"code"]] isEqualToString:@"200"]) {
                    [CLData sharedClass].token = responseObject[@"data"][@"token"];
                    

                    
                    NSString *tmpStr = [CLTool cl_getUser:@"jobNumber"];
                    [CLData sharedClass].jobNumber = tmpStr;
                    if(tmpStr.length != 0){
                        
                        [ZBRequestManager requestWithConfig:^(ZBURLRequest *request){
                            request.path=url_login;
                            request.methodType=ZBMethodTypePOST;
                            request.parameters = @{@"workCode":[CLData sharedClass].jobNumber};
                            request.userInfo = @{@"type":@"999"};
                        }  success:^(id responseObject,ZBURLRequest * request){
                            if ([[NSString stringWithFormat:@"%@",responseObject[@"code"]] isEqualToString:@"200"]) {
                                [CLData sharedClass].homeUrl = responseObject[@"data"][@"url"];
                                
                                CLMainViewController *vc = [[CLMainViewController alloc]init];
                                vc.address = [CLData sharedClass].homeUrl;
                                [self.navigationController pushViewController:vc animated:YES];
                            }else{
                                [CLTool cl_showFail:responseObject[@"msg"] block:^{
                                    
                                }];
                            }
                            
                        } failure:^(NSError * _Nullable error) {
                            [CLTool cl_showFail:@"请求错误" block:^{
                                
                            }];
                        } finished:^(id responseObject, NSError *error, ZBURLRequest *request) {
                            NSLog(@"请求完成");
                        }];
                        
                    }else{

                    }
                }else{
                    [CLTool cl_showFail:responseObject[@"msg"] block:^{
                        
                    }];
                }
                
                
            } failure:^(NSError * _Nullable error) {
                [CLTool cl_showFail:@"请求错误" block:^{
                    
                }];

            } finished:^(id responseObject, NSError *error, ZBURLRequest *request) {
                NSLog(@"请求完成");
            }];
            
        }
    }];
        

}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
- (void)cl_loginBtn{
    WWKSSOReq *req = [[WWKSSOReq alloc] init];
    req.state = [CLTool getRandomStringWithNum:51];
    [WWKApi sendReq:req];
    
//    [CLData sharedClass].homeUrl = @"https://jz.721211.xyz/ceshi.html";
//    CLMainViewController *vc = [[CLMainViewController alloc]init];
//    vc.address = [CLData sharedClass].homeUrl;
//    [self.navigationController pushViewController:vc animated:YES];
}
- (void)cl_workloginBtn{


    CLWorkViewController *vc = [[CLWorkViewController alloc]init];
    vc.address = url_one_login;
//    vc.address = @"https://ssouat.yuhong.com.cn/cp/tt/index.html";
    [self.navigationController pushViewController:vc animated:YES];


  //  [self takePhoto];
}
- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        // 无相机权限 做一个友好的提示
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takePhoto];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else {
        [self pushImagePickerController];
    }
}
// 调用相机
- (void)pushImagePickerController {


    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerVc.sourceType = sourceType;
        NSMutableArray *mediaTypes = [NSMutableArray array];

        if (mediaTypes.count) {
            _imagePickerVc.mediaTypes = mediaTypes;
        }
        [self presentViewController:_imagePickerVc animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}
- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        _imagePickerVc.sourceType=UIImagePickerControllerSourceTypeCamera;//设置image picker的来源，这里设置为摄像头
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (@available(iOS 9, *)) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
 
    }
    return _imagePickerVc;
}
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    [CLTool cl_showLoading];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    NSData *data = UIImageJPEGRepresentation(image, 1.0f);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];

}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}
@end
